package com.zjcode.cdcer.config;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zjcode.cdcer.utils.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.UUID;

/**
 * @Desc 国家人群筛查平台上报 登录配置中心
 * 接口文档 http://herdapi.zaozhenzaozhi.com/doc/dist/#/
 * @author bqyang
 */
@Slf4j
public class DataPushConfig {

    // Token请求头
    public static final String TOKEN_HEADER = "Authorization";
    // Token前缀
    public static final String TOKEN_PREFIX = "Bearer ";

    private final static String secret = "7d3ac519b88c3453ded4de1191ce752d";

    private final static String clientId = "638a6f15404fc15f9cf73bf2aa1616ba";

    // 接口域名地址
    private final static String requestUrl = "http://herdapi.zaozhenzaozhi.com";
    // 无验证码方式登录
    private final static String loginApi = requestUrl + "/apiadmin/login2";
    // 内镜/病理报告单上传
    public final static String uplodaFileAPi = requestUrl + "/apiadmin/files/uploadFile";
    // 知情同意书上传
    public final static String uploadOneApi = requestUrl + "/apiadmin/files/uploadOne";

    /**
     *  自测表更新
     */
    public final static String selfTestApi = requestUrl + "/apiadmin/questionaires/updatesave";

    /**
     *  数据上报创建
     */
    public final static String createApi = requestUrl + "/apiadmin/formal/create";

    /**
     *  数据上报查询
     */
    public final static String indexApi = requestUrl + "/apiadmin/formal/index";
    /**
     *  数据上报 更新
     */
    public final static String updateApi = requestUrl + "/apiadmin/formal/update";


    // 登录平台账号/密码
    /*private final static String username = "34010401g";
    private final static String password = "AHcdc2022";
    private final static String username = "34080201";
    private final static String password = "Aqyy@34080201";
  */
    /**
     *  平台接口登录 返回 token
     * @return
     */
    public static String getLoginToken(String username, String password) {
        String codeStr = StringUtils.EMPTY;
        try {
            String nonce = UUID.randomUUID().toString().replace("-", "");
            long currentTime = System.currentTimeMillis();
            String tenDigitTimestamp = Long.toString(currentTime / 1000);

            String signature = getSignature(tenDigitTimestamp + nonce, secret);

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode objectNode = objectMapper.createObjectNode();
            objectNode.put("client_id", clientId);
            objectNode.put("nonce", nonce);
            objectNode.put("timestamp", tenDigitTimestamp);
            objectNode.put("signature", signature);
            objectNode.put("user_name", username);
            objectNode.put("password", password);

            ResponseEntity<String> response = RestTemplateUtil.restTemplatePost(loginApi, objectNode);

            if (response.getStatusCode().is2xxSuccessful()) {
                String result = response.getBody();
                log.info("=====登录国家平台返回结果：{}", result);
                JSONObject json = JSONObject.parseObject(result);
                Integer code = json.getInteger("code");
                if ( code != HttpStatus.OK.value()){
                    return codeStr;
                }
                codeStr = json.getString("data");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return codeStr;
    }

    /**
     * 使用 HMAC-SHA1 签名算法对data进行签名
     * @param data 被签名的字符串
     * @param key  密钥
     * @return 加密后的字符串
     */
    public static String getSignature(String data, String key) throws Exception {
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        //用给定密钥初始化 Mac 对象
        mac.init(signinKey);
        //完成 Mac 操作
        byte[] rawHmac = mac.doFinal(data.getBytes());
        return byte2hex(rawHmac);
    }

    private static String byte2hex(final byte[] b) {
        String hs = "";
        String stmp = "";
        for (byte value : b) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式。
            stmp = (Integer.toHexString(value & 0xFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }
}
